package cn.jorian.framework.controller;

import cn.jorian.framework.bean.ResponseResult;
import cn.jorian.framework.bean.UserBean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    @PostMapping("/upload")
    public ResponseResult<UserBean> upload(@RequestPart("file") MultipartFile file, @RequestPart("user") UserBean userBean) {
        if (file.isEmpty()) {
            return ResponseResult.fail("文件为空");
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        try {
            byte[] bytes = file.getBytes();
            File newFile = new File("./" + fileName);
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(newFile);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ResponseResult<UserBean> result = ResponseResult.success();
        result.setData(userBean);
        return result;
    }
}
